package role_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

// GetRoleByKeyword 关键字查询用户
func GetRoleByKeyword(keyward string) *gorm.DB {
	tx := database.DB.Model(new(models.Role)).Select("id,name,desc, created_at,update_at,deleted_flag,is_admin,sort")
	if keyward != "" {
		tx = tx.Where("name LIKE ?", "%"+keyward+"%")
	}
	return tx
}

// GetRoleList 获取所有角色
func GetRoleList(c *gin.Context) {
	list := make([]*AllRoleListReply, 0)
	err := database.DB.Model(new(models.Role)).Where("deleted_flag !=1 ").Find(&list).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "获取角色列表失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": list,
	})
}

// GetRoleDetailById 根据id获取角色信息
func GetRoleDetailById(id int64) (*models.Role, error) {
	sr := new(models.Role)
	err := database.DB.Model(new(models.Role)).Where("id = ?", id).First(sr).Error
	return sr, err
}

// GetRoleMenuId 获取指定角色的菜单
func GetRoleMenuId(roleId int64, isAdmin bool) ([]int64, error) {
	tx := new(gorm.DB)
	data := make([]int64, 0)
	if isAdmin {
		tx = database.DB.Model(new(models.Menu)).Select("id").Order("sort ASC")
	} else {
		tx = database.DB.Model(new(models.RoleMenu)).Select("sm.id").Joins("LEFT JOIN menu_router sm on sm.id=role_menu.menu_id").
			Where("role_menu.role_id = ?", roleId).Order("sm.order ASC")
	}
	err := tx.Scan(&data).Error
	return data, err
}

// GetRoleDetail 根据id查角色信息
func GetRoleDetail(c *gin.Context) {
	id := c.Request.URL.Query().Get("id")
	if id == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	Id, _ := strconv.Atoi(id)
	data := new(GetRoleDetailReply)
	sr, err := GetRoleDetailById(int64(Id))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	data.Name = sr.Name
	data.ID = sr.ID
	data.Sort = sr.Sort
	data.IsAdmin = sr.IsAdmin
	menuIds, err := GetRoleMenuId(sr.ID, sr.IsAdmin)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msd":  "系统错误",
		})
		return
	}
	data.MenuId = menuIds
	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"msg":    "操作成功",
		"result": data,
	})

}
